<?php
namespace app\sso\controller;

use tp5_lib\common\controller\BaseController;
use tp5_lib\user\model\UserModel;
use think\facade\Session;

/**
 * 单点登录
 */
class IndexController extends BaseController
{
    static public function auth()
    {
        $instance=new static();
        return $instance->checkTicket();
    }
    /**
     * 检查并返回登录状态
     */
    public function index()
    {
        $user=$this->checkLogin();
        $url=input("redirect_url","");
        $url=$this->appendTicket($user,$url);
        $this->redirect($url);
    }
    protected function appendTicket($user,$url)
    {
        $uid=$user["user_id"];
        $time=time();
        $ticket=$this->genTicket($user,$time);
        $separator = strpos($url,"?") !== false ? "&" : "?";
        return $url.$separator."uid=".$uid."&ticket=".$ticket."&time=".$time;
    }
    protected function checkTicket()
    {
        $data=input();
        if(!empty($data["ticket"])){
            if(empty($data["uid"]) || empty($data["time"])){
                echo "缺少uid||time参数";
                exit;
            }
            if(intval($data["time"]) + 60 > time()){
                echo "票据过期";
                exit;
            }
            $model=new UserModel();
            $user=$model->db()->where(["id",$data["uid"]])->find();
            $ticket=$this->genTicket($user,$data["time"]);
            if($ticket !== $data["ticket"]){
                echo "验证失败";
                exit;
            }
            Session::set("user",$user);
            unset($data["ticket"],$data["uid"],$data["time"]);
            $url=$this->request->baseUrl() . "?" . http_build_query($data);
            $this->redirect($url);
        }
    }
    /**
     * 生成票据
     * @param string[] $user 用户数据
     * @param string|int $time 用户数据
     * @return string
     */
    public function genTicket($user,$time)
    {
        return md5($user["user_id"].$user["user_name"].$user["password"].$user["last_ip"].$user["mobile_phone"].$time);
    }
}
